package com.xiang.utils;

import com.xiang.config.EsConfig;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 范围查询
 *
 * @author xiangtianlei@gogpay.cn
 * @date 2023-01-30
 */
public class RangeQuery {
    RestHighLevelClient client = EsConfig.getClient();
    Logger logger = LoggerFactory.getLogger(RangeQuery.class);

    /**
     * 范围查询
     */
    @Test
    public void rangeQuery() throws IOException {
        // 创建查询request
        SearchRequest request = new SearchRequest(EsConfig.INDEX_NAME);
        // 封装查询语句
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.rangeQuery("age").gte(20).lte(40));
        request.source(builder);
        // 执行查询
        SearchResponse res = client.search(request, RequestOptions.DEFAULT);
        logger.info("查询DSL语句：{}", request.source().toString());
        for (SearchHit hit : res.getHits().getHits()) {
            logger.info("查询结果：{}", hit.getSourceAsMap());
        }

    }

}
